package com.whj.wkpt.controller;

import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 用户管理相关功能
    
    @GetMapping("/users")
    public String listUsers(Model model) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("users", users);
        return "admin/users";
    }
    
    @GetMapping("/users/create")
    public String createUserForm(Model model) {
        model.addAttribute("user", new User());
        return "admin/user-create";
    }
    
    @PostMapping("/users")
    public String createUser(@ModelAttribute("user") User user, Model model) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            model.addAttribute("usernameError", "用户名已存在");
            return "admin/user-create";
        }

        // 检查邮箱是否已存在
        if (userService.existsByEmail(user.getEmail())) {
            model.addAttribute("emailError", "邮箱已被注册");
            return "admin/user-create";
        }
        
        // 设置创建和更新时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        // 加密密码
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
        
        // 保存用户
        userService.save(user);
        
        return "redirect:/admin/users";
    }

    @GetMapping("/users/{id}")
    public String viewUser(@PathVariable("id") Long id, Model model) {
        User user = userService.findById(id).orElse(new User());
        model.addAttribute("user", user);
        return "admin/user-detail";
    }
    
    @GetMapping("/users/edit/{id}")
    public String editUserForm(@PathVariable("id") Long id, Model model) {
        User user = userService.findById(id).orElse(new User());
        model.addAttribute("user", user);
        return "admin/user-edit";
    }
    
    @PostMapping("/users/update/{id}")
    public String updateUser(@PathVariable("id") Long id, @ModelAttribute("user") User user) {
        User existingUser = userService.findById(id).orElse(new User());
        if (existingUser != null) {
            // 更新用户信息，但保留用户名不变
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            existingUser.setRole(user.getRole());
            userService.updateUser(existingUser);
        }
        return "redirect:/admin/users";
    }

    @GetMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        return "redirect:/admin/users";
    }
    
    // 任务管理相关功能
    
    @GetMapping("/tasks")
    public String listTasks(Model model) {
        List<Task> tasks = taskService.findAllTasks();
        model.addAttribute("tasks", tasks);
        return "admin/tasks";
    }
    
    @GetMapping("/tasks/{id}")
    public String viewTask(@PathVariable("id") Long id, Model model) {
        Task task = taskService.findById(id);
        User employer = null;
        if (task != null) {
            employer = userService.findById(task.getEmployerId()).orElse(null);
        }
        model.addAttribute("task", task);
        model.addAttribute("employer", employer);
        return "admin/task-detail";
    }
    
    @GetMapping("/tasks/edit/{id}")
    public String editTaskForm(@PathVariable("id") Long id, Model model) {
        Task task = taskService.findById(id);
        List<User> employers = userService.findAllUsers().stream()
                .filter(user -> "employer".equals(user.getRole()))
                .toList();
        model.addAttribute("task", task);
        model.addAttribute("employers", employers);
        return "admin/task-edit";
    }
    
    @PostMapping("/tasks/update/{id}")
    public String updateTask(@PathVariable("id") Long id, @ModelAttribute("task") Task task) {
        Task existingTask = taskService.findById(id);
        if (existingTask != null) {
            // 保留关键字段不变
            task.setTaskId(id);
            task.setCreateTime(existingTask.getCreateTime());
            task.setPublishDate(existingTask.getPublishDate());
            task.setUpdateTime(LocalDateTime.now());
            taskService.updateTask(task);
        }
        return "redirect:/admin/tasks";
    }
    
    @GetMapping("/tasks/delete/{id}")
    public String deleteTask(@PathVariable("id") Long id) {
        taskService.deleteTask(id);
        return "redirect:/admin/tasks";
    }
}